const User = require('../model/user.model')
class UserService {
    //添加用户
    async createUser(userName, password,phone,role) {
        const res = await User.create({ userName, password,phone,role })
        return res.dataValues
    }
    // 获取某个用户信息
    async getOneUserInfo({ id,userName,phone,role}) {
        const whereOpt = {}
        id && Object.assign(whereOpt, { id })
        userName && Object.assign(whereOpt, { userName })
        phone&& Object.assign(whereOpt, { phone})
        role && Object.assign(whereOpt, { role })

        const res = await User.findOne({
            attributes: ['id', 'userName', 'password', 'role'],
            where: whereOpt
        })

        return res ? res.dataValues : null
    }
    // 获取所有用户信息
    async getAllUserInfo(userName,phone,role,pageNum, pageSize) {
        const whereOpt = {}

        userName && Object.assign(whereOpt, { userName })
        phone&& Object.assign(whereOpt, { phone})
        role && Object.assign(whereOpt, { role })
        const offset = (pageNum - 1) * pageSize
        const { count, rows }  = await User.findAndCountAll({
            attributes: ['id', 'userName','phone','password', 'role'],
            offset: offset,
            limit: pageSize * 1,
            where: whereOpt
        }
        )
        return {
            
            pageNum,
            pageSize,
            total: count,
            rows
        }
    }
    
    // 根据ID删除数据  
    async deleteDataById(id) {
        const res = await User.destroy({
            where: { id }
        })
        return res
    }
    // 根据ID修改数据
    async updateDataById({ id, userName, phone, role }) {
        const whereOpt = { id }
        const newUser = {}
        userName && Object.assign(newUser, { userName })
        phone&& Object.assign(newUser, { phone})
        role && Object.assign(newUser, { role })

        const res = await User.update(newUser, { where: whereOpt })
        console.log(res)

        return res[0] > 0 ? true : false
    }
}

module.exports = new UserService()